package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.mall.dto.ClearCartItemRequest;
import com.cskaoyan.mall.dto.ClearCartItemResponse;
import com.cskaoyan.shopping.converter.CartItemConverter;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.dto.*;
import com.cskaoyan.shopping.service.ICartService;
import org.redisson.Redisson;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @auther cskaoyan
 * @date 2022/6/16:16:34
 */
@Service
public class ICartSeviceImpl implements ICartService {


    @Autowired
    ItemMapper itemMapper;


    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse cartListByIdResponse = new CartListByIdResponse();
        List<CartProductDto> list = new ArrayList<>();
        try {
            Config config = new Config();
            SingleServerConfig singleServerConfig = config.useSingleServer().setAddress("redis://localhost:6379");
            RedissonClient redissonClient = Redisson.create(config);
            RMap<Object, Object> map = redissonClient.getMap(request.getUserId().toString());
            for (Map.Entry<Object, Object> o : map.entrySet()) {
                list.add(((CartProductDto) o.getValue()));
                CartProductDto value = (CartProductDto) o.getValue();
                System.out.println(value.getProductNum());
            }
            cartListByIdResponse.setCartProductDtos(list);
            cartListByIdResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            cartListByIdResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(cartListByIdResponse, e);
        }

        return cartListByIdResponse;
    }

    @Override
    public AddCartResponse addToCart(AddCartRequest request) {

        AddCartResponse addCartResponse = new AddCartResponse();
        try {
            request.requestCheck();
            Item item = itemMapper.selectByPrimaryKey(request.getItemId());
            CartProductDto cartProductDto = CartItemConverter.item2Dto(item);
            cartProductDto.setProductNum(Long.valueOf(request.getNum()));
            //默认选择
            cartProductDto.setChecked("true");
            //redis存储
            Config config = new Config();
            SingleServerConfig singleServerConfig = config.useSingleServer().setAddress("redis://localhost:6379");
            RedissonClient redissonClient = Redisson.create(config);
            RMap<Object, Object> map = redissonClient.getMap(request.getUserId().toString());

            if (map.containsKey(request.getItemId().toString())) {
                CartProductDto oldCart = (CartProductDto) map.get(request.getItemId().toString());
                cartProductDto.setProductNum(cartProductDto.getProductNum() + oldCart.getProductNum());
                map.put(request.getItemId().toString(), cartProductDto);
            } else {
                map.put(request.getItemId().toString(), cartProductDto);
            }


            addCartResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            addCartResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(addCartResponse, e);
        }
        return addCartResponse;
    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse updateCartNumResponse = new UpdateCartNumResponse();
        try {
            request.requestCheck();
            Config config = new Config();
            SingleServerConfig singleServerConfig = config.useSingleServer().setAddress("redis://localhost:6379");
            RedissonClient redissonClient = Redisson.create(config);
            RMap<Object, Object> map = redissonClient.getMap(request.getUserId().toString());

            // CartProductDto product = (CartProductDto) map.get(request.getItemId().toString());
            // product.setProductNum(product.getProductNum()+request.getNum());
            // map.put(request.getItemId().toString(),product);
            // System.out.println("update");
            // System.out.println(product.getProductNum()+request.getNum());

            Item item = itemMapper.selectByPrimaryKey(request.getItemId());
            CartProductDto cartProductDto = CartItemConverter.item2Dto(item);
            cartProductDto.setProductNum(request.getNum().longValue());
            cartProductDto.setChecked(request.getChecked());
            map.put(request.getItemId().toString(), cartProductDto);
            updateCartNumResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            updateCartNumResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(updateCartNumResponse, e);
        }

        return updateCartNumResponse;
    }

    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse response = new CheckAllItemResponse();
        try {
            request.requestCheck();
            Config config = new Config();
            SingleServerConfig singleServerConfig = config.useSingleServer().setAddress("redis://localhost:6379");
            RedissonClient redissonClient = Redisson.create(config);
            RMap<Object, Object> map = redissonClient.getMap(request.getUserId().toString());

            for (Map.Entry<Object, Object> o : map.entrySet()) {
                CartProductDto value = (CartProductDto) o.getValue();
                value.setChecked(request.getChecked());
                map.put(o.getKey(), value);
            }

            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse response = new DeleteCartItemResponse();
        try {
            request.requestCheck();
            Config config = new Config();
            SingleServerConfig singleServerConfig = config.useSingleServer().setAddress("redis://localhost:6379");
            RedissonClient redissonClient = Redisson.create(config);
            RMap<Object, Object> map = redissonClient.getMap(request.getUserId().toString());
            for (RMap.Entry<Object, Object> o : map.entrySet()) {
                CartProductDto value = (CartProductDto) o.getValue();
                Long key = value.getProductId();
                //long key = (long)o.getKey;
                if (key.equals(request.getItemId())) {
                    map.remove(o.getKey());
                }
            }

            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResposne response = new DeleteCheckedItemResposne();
        try {
            request.requestCheck();
            Config config = new Config();
            SingleServerConfig singleServerConfig = config.useSingleServer().setAddress("redis://localhost:6379");
            RedissonClient redissonClient = Redisson.create(config);
            RMap<Object, Object> map = redissonClient.getMap(request.getUserId().toString());

            for (RMap.Entry<Object, Object> o : map.entrySet()) {
                CartProductDto value = (CartProductDto) o.getValue();
                if (value.getChecked() != null && value.getChecked().equals("true")) {
                    map.remove(o.getKey());
                }
            }
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;

    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        ClearCartItemResponse response = new ClearCartItemResponse();
        try {
            request.requestCheck();
            Config config = new Config();
            SingleServerConfig singleServerConfig = config.useSingleServer().setAddress("redis://localhost:6379");
            RedissonClient redissonClient = Redisson.create(config);
            RMap<Object, Object> map = redissonClient.getMap(request.getUserId().toString());

            map.clear();

            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }
}
